//
//  MAMapDetailViewController.m
//  YunGui
//
//  Created by HanenDev on 16/4/7.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "MAMapDetailViewController.h"
#import "UIView+Extension.h"
#import "Macro.h"
#import "SQButton.h"
#import "MapButton.h"
#import "MAMapCell.h"
#import "MARouteLineVC.h"

#define STARTX [UIView getWidth:20]
#define cellH 65.0f

@interface MAMapDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITextField    *_myTF;
    UITextField    *_addrTF;
    UITableView      * _busTableView;
    UITableView      * _carTableView;
    UITableView      * _walkTableView;
    
    int      _lastTag;
    BOOL     isChanged;
    BOOL     isWalking;
    BOOL     first;
    
    int      btnTag;
}
@property(nonatomic,assign)CLLocationCoordinate2D endCoordinate;
@property(nonatomic,strong)NSArray      *drivingArray;
@property(nonatomic,strong)NSArray      *transitArray;
@property(nonatomic,strong)NSArray      *walkingArray;

@end

@implementation MAMapDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = GrayBackColor;
    self.navigationItem.title = @"地图详情";
    self.navigationItem.hidesBackButton = YES;
    
    self.navigationItem.leftBarButtonItem = [ViewTool getBarButtonItemWithTarget:self WithString:@"back" WithAction:@selector(goToBack)];
    
    //初始化检索对象
    _searchApi = [[AMapSearchAPI alloc] init];
    _searchApi.delegate = self;
    
    [self createView];
    isChanged = NO;
}
-(void)createView
{
    
    CGFloat locaH  = 100;
    CGFloat startX = [UIView getWidth:20];
    CGFloat space = 15;
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, locaH)];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    
    UIButton *sqBtn = [[UIButton alloc]initWithFrame:CGRectMake(startX, (locaH - 30)/2, 30, 30)];
    [sqBtn setImage:[UIImage imageNamed:@"Btn_Normal_Jiaohu"] forState:UIControlStateNormal];
    [sqBtn addTarget:self action:@selector(adChangedClick:) forControlEvents:UIControlEventTouchUpInside];
    sqBtn.selected = NO;
    [bgView addSubview:sqBtn];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(sqBtn.maxX + space, locaH/2 - 1, kScreenWidth, 1)];
    lineView.backgroundColor = GRAYLINECOLOR;
    [bgView addSubview:lineView];
    
    UIImageView * startImage = [[UIImageView alloc]initWithFrame:CGRectMake(sqBtn.maxX+space, (locaH/2 - 15)/2, 15, 15)];
    startImage.image = [UIImage imageNamed:@"Btn_Normal_Wodeweizhi"];
    [bgView addSubview:startImage];
    
    _myTF = [[UITextField alloc]initWithFrame:CGRectMake(startImage.maxX + space, (locaH/2 - 40)/2, kScreenWidth-startImage.maxX - STARTX, 40)];
    _myTF.text = @"我的位置";
    [_myTF setValue:UIColorFromRGB(0xe5e5e5) forKeyPath:@"_placeholderLabel.textColor"];
    [_myTF setValue:[UIFont systemFontOfSize:16.0f] forKeyPath:@"_placeholderLabel.font"];
    _myTF.enabled = NO;
    _myTF.delegate = self;
    [bgView addSubview:_myTF];
    
    UIImageView * endImage=[[UIImageView alloc]initWithFrame:CGRectMake(sqBtn.maxX+space, lineView.maxY + (locaH/2 - 15)/2, 15, 15)];
    endImage.image = [UIImage imageNamed:@"Btn_Normal_Daodadi"];
    [bgView addSubview:endImage];
    
    _addrTF = [[UITextField alloc]initWithFrame:CGRectMake(endImage.maxX + space, lineView.maxY + (locaH/2 - 40)/2, kScreenWidth-endImage.maxX - STARTX, 40)];
    _addrTF.placeholder = @"请输入终点...";
    _addrTF.enabled = NO;
    _addrTF.text = self.districtStr;
    [_addrTF setValue:UIColorFromRGB(0xe5e5e5) forKeyPath:@"_placeholderLabel.textColor"];
    [_addrTF setValue:[UIFont systemFontOfSize:16.0f] forKeyPath:@"_placeholderLabel.font"];
    _addrTF.delegate = self;
    [bgView addSubview:_addrTF];
    
    
    UIView *carView = [[UIView alloc]initWithFrame:CGRectMake(0, bgView.maxY, kScreenWidth, 50)];
    carView.tag = 1230;
    [self.view addSubview:carView];
    
    NSArray * titleArray=@[@"Btn_Normal_Gongjiao",@"Btn_Normal_Jiache",@"Btn_Normal_ Buxing"];
    
    NSArray*irr=@[@"公交",@"驾车",@"步行"];
    
    for (int i=0; i<titleArray.count; i++)
    {
        CGFloat btnW = 70;
        CGFloat space = (kScreenWidth - 2*STARTX - 3*btnW)/2;
        MapButton *btn=[[MapButton alloc]initWithFrame:CGRectMake(STARTX +(btnW + space)*i, 0, btnW, 50)];
        [btn setImage:[UIImage imageNamed:titleArray[i]] forState:UIControlStateNormal];
        [btn setTitle:irr[i] forState:UIControlStateNormal];
        [btn setTitleColor:BLACKCOLOR forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:15.0f];
        btn.tag=1000+i;
        [btn addTarget:self action:@selector(searLine:) forControlEvents:UIControlEventTouchUpInside];
        [carView addSubview:btn];
        
        UIView *line = [[UIView alloc]init];
        line.backgroundColor = GrayLineColor;
        [carView addSubview:line];
        
        if (i == 1) {
            line.frame = CGRectMake(STARTX + btnW +space/2, 10, 1, 30);
        }if (i == 2) {
            line.frame = CGRectMake(STARTX + btnW*2 +space/2+space, 10, 1, 30);
        }
    }
    _lastTag = 1000;
    MapButton *btn = (MapButton *)[carView viewWithTag:_lastTag];
    [btn setImage:[UIImage imageNamed:@"Btn_Push_Gongjiao"] forState:UIControlStateNormal];
    
    [self initTableView];
}
- (void)initTableView{
    UIView *view=[self.view viewWithTag:1230];
    
    _carTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, view.maxY, kScreenWidth, kScreenHeight-view.maxY - 64)];
    _carTableView.delegate=self;
    _carTableView.dataSource=self;
    _carTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _carTableView.backgroundColor = GrayBackColor;
    
    _busTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, view.maxY, kScreenWidth, kScreenHeight-view.maxY -64)];
    _busTableView.delegate=self;
    _busTableView.dataSource=self;
    _busTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _busTableView.backgroundColor = GrayBackColor;
    
    _walkTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, view.maxY, kScreenWidth, kScreenHeight-view.maxY -64)];
    _walkTableView.delegate=self;
    _walkTableView.dataSource=self;
    _walkTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _walkTableView.backgroundColor = GrayBackColor;
    
    
    [self.view addSubview:_busTableView];
    
    AMapTransitRouteSearchRequest *transitRoute = [[AMapTransitRouteSearchRequest alloc]init];
    transitRoute.strategy = 0;/// 公交换乘策略：0-最快捷；1-最经济；2-最少换乘；3-最少步行；4-最舒适；5-不乘地铁
    transitRoute.city = self.cityStr;
    transitRoute.requireExtension = YES;//!< 是否返回扩展信息，默认为 NO
    transitRoute.origin = [AMapGeoPoint locationWithLatitude:self.myLocation.latitude longitude:self.myLocation.longitude];//出发地
    transitRoute.destination = [AMapGeoPoint locationWithLatitude:self.endLoc.latitude longitude:self.endLoc.longitude];//目的地
    [_searchApi AMapTransitRouteSearch:transitRoute];
    
    first = YES;
    
}
- (void)searLine:(MapButton *)sender{
    NSArray * titleArray=@[@"Btn_Normal_Gongjiao",@"Btn_Normal_Jiache",@"Btn_Normal_ Buxing"];
    NSArray * imageArr = @[@"Btn_Push_Gongjiao",@"Btn_Push_Jiache",@"Btn_Push_Buxing"];
    MapButton *btn = (MapButton *)[self.view viewWithTag:_lastTag];
    [btn setImage:[UIImage imageNamed:titleArray[_lastTag - 1000]] forState:UIControlStateNormal];
    
    long count  = sender.tag - 1000;
    [sender setImage:[UIImage imageNamed:imageArr[count]] forState:UIControlStateNormal];
    
    _lastTag = (int)sender.tag;
    
    CLLocationCoordinate2D  coordinate1;
    CLLocationCoordinate2D  coordinate2;
    if (isChanged == NO) {
        coordinate1 = self.myLocation;
        coordinate2 = self.endLoc;
        
    }else{
        coordinate1 = self.endLoc;
        coordinate2 = self.myLocation;
        
    }
    
    btnTag = (int)sender.tag;
    
    switch (sender.tag) {
        case 1000://公交路径查询
        {
            [self.view addSubview:_busTableView];
            
            AMapTransitRouteSearchRequest *transitRoute = [[AMapTransitRouteSearchRequest alloc]init];
            transitRoute.strategy = 0;/// 公交换乘策略：0-最快捷；1-最经济；2-最少换乘；3-最少步行；4-最舒适；5-不乘地铁
            transitRoute.city = self.cityStr;
            transitRoute.requireExtension = YES;//!< 是否返回扩展信息，默认为 NO
            transitRoute.origin = [AMapGeoPoint locationWithLatitude:coordinate1.latitude longitude:coordinate1.longitude];//出发地
            transitRoute.destination = [AMapGeoPoint locationWithLatitude:coordinate2.latitude longitude:coordinate2.longitude];//目的地
            [_searchApi AMapTransitRouteSearch:transitRoute];
            
        }
            break;
        case 1001://驾车路径查询
        {
            isWalking = NO;
            [self.view addSubview:_carTableView];

            AMapDrivingRouteSearchRequest *drivingRoute = [[AMapDrivingRouteSearchRequest alloc]init];
            drivingRoute.strategy = 5;/// 驾车导航策略：0-速度优先（时间）；5-多策略（同时使用速度优先、费用优先、距离优先三个策略）
            drivingRoute.requireExtension = YES;
            drivingRoute.origin = [AMapGeoPoint locationWithLatitude:coordinate1.latitude longitude:coordinate1.longitude];
            drivingRoute.destination = [AMapGeoPoint locationWithLatitude:coordinate2.latitude longitude:coordinate2.longitude];
            [_searchApi AMapDrivingRouteSearch:drivingRoute];
            
        }
            break;
        case 1002://步行路径查询
        {
            isWalking = YES;
            [self.view addSubview:_walkTableView];
            
            AMapWalkingRouteSearchRequest *walkingRoute = [[AMapWalkingRouteSearchRequest alloc]init];
            walkingRoute.multipath = 0;// 是否提供备选步行方案: 0-只提供一条步行方案; 1-提供备选步行方案(有可能无备选方案)
            walkingRoute.origin = [AMapGeoPoint locationWithLatitude:coordinate1.latitude longitude:coordinate1.longitude];
            walkingRoute.destination = [AMapGeoPoint locationWithLatitude:coordinate2.latitude longitude:coordinate2.longitude];
            [_searchApi AMapWalkingRouteSearch:walkingRoute];
            
        }
            break;
        default:
            break;
    }
    
    
}
-(void)adChangedClick:(UIButton *)btn
{
    
    
    if (btn.selected==NO){
        isChanged = YES;
        
        _myTF.text=self.districtStr;
        _addrTF.text=@"我的位置";
        btn.selected=YES;
    }else{
        isChanged = NO;
        _myTF.text=@"我的位置";
        _addrTF.text=self.districtStr;
        btn.selected=NO;
    }
    
}
#pragma mark
#pragma mark  ------地图相关的代理
- (void)onGeocodeSearchDone:(AMapGeocodeSearchRequest *)request response:(AMapGeocodeSearchResponse *)response{
    
    if (response.geocodes.count == 0){
        return;
    }
    
    AMapGeocode *geo = response.geocodes[0];
    self.endCoordinate = (CLLocationCoordinate2D){geo.location.latitude,geo.location.longitude};
    NSLog(@"%f",self.endCoordinate.latitude);
}
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response{
    if (response.route == nil){
        
        return;
    }
    
    if (first) {
        self.transitArray = response.route.transits;
    }
    
    if (btnTag == 1000) {
        
        self.transitArray = response.route.transits;
        
    }else if (btnTag == 1001) {
        
        self.drivingArray = response.route.paths;
        
    }else if (btnTag == 1002) {
        
        self.walkingArray = response.route.paths;
        
    }
    
    
    [_carTableView reloadData];
    [_busTableView reloadData];
    [_walkTableView reloadData];
    
    
    
    
    NSLog(@"%@+++++walkingArray++++++",self.walkingArray);
    
    
}
#pragma mark
#pragma mark  ------tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _busTableView) {
        return self.transitArray.count;
    }else if (tableView == _carTableView){
        return self.drivingArray.count;
    }else if (tableView == _walkTableView){
        return self.walkingArray.count;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return cellH;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"mapcell";
    MAMapCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[MAMapCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    cell.backgroundColor = GrayBackColor;
    if (tableView == _busTableView) {
        AMapTransit *transit = self.transitArray[indexPath.row];
        cell.timeLabel.text = [NSString stringWithFormat:@"%d分钟",(int)transit.duration/60];
        cell.distanceLabel.text = [NSString stringWithFormat:@"%.0d公里",(int)transit.distance/1000];
        cell.walkLabel.text = [NSString stringWithFormat:@"步行%d米",(int)transit.walkingDistance];
        
        NSString *route = @"";
        AMapTransit *tran = self.transitArray[indexPath.row];
        
        for (int i=0; i<tran.segments.count; i++) {
            
        AMapSegment *segment = tran.segments[i];
        for (int j=0; j<segment.buslines.count; j++) {
            AMapBusLine *busLine = segment.buslines[j];
            NSString *string = [busLine.name componentsSeparatedByString:@"("][0];
            if ([route isEqualToString:@""]) {
                route= string;
            }else{
                route = [NSString stringWithFormat:@"%@ > %@",route,string];
            }
            
        }
    }
        
        cell.nameLabel.text = route;
        
    }else if (tableView == _carTableView){
        AMapPath *path = _drivingArray[indexPath.row];
        cell.nameLabel.text = @"驾车方案";
        cell.timeLabel.text = [NSString stringWithFormat:@"%d分钟",(int)path.duration/60];
        cell.distanceLabel.text = [NSString stringWithFormat:@"%d公里",(int)path.distance/1000];
        cell.walkLabel.text = [NSString stringWithFormat:@"%@",path.strategy];
    }else if (tableView == _walkTableView){
        AMapPath *path = _walkingArray[indexPath.row];
        cell.nameLabel.text = @"步行方案";
        cell.timeLabel.text = [NSString stringWithFormat:@"%d分钟",(int)path.duration/60];
        cell.distanceLabel.text = [NSString stringWithFormat:@"%d公里",(int)path.distance/1000];
        cell.walkLabel.text = [NSString stringWithFormat:@"%@",path.strategy];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MARouteLineVC *routeVC= [[MARouteLineVC alloc]init];
    if (isChanged == NO) {
        routeVC.startStr = @"我的位置";
        routeVC.endStr = _districtStr;
    }else{
        routeVC.startStr = _districtStr;
        routeVC.endStr = @"我的位置";
    }
    if (tableView == _walkTableView) {
        
        AMapPath *path=self.walkingArray[indexPath.row];
        routeVC.routeArray=path.steps;
        
        [self.navigationController pushViewController:routeVC animated:NO];
        
    }
    if (tableView == _busTableView){
        
        AMapTransit *tran = self.transitArray[indexPath.row];
        routeVC.routeArray = tran.segments;
        routeVC.type = 2222;
        
        [self.navigationController pushViewController:routeVC animated:NO];
    }
    if (tableView == _carTableView){
        AMapPath *path = _drivingArray[indexPath.row];
        routeVC.routeArray=path.steps;
        
        [self.navigationController pushViewController:routeVC animated:NO];
    }

}

- (void)goToBack{
     [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
